from flask import request
from api import db
from api.role import role_api, role_blue
from api.utils.response import to_response
from api.utils.baseResource import BaseResource
from api.models import Role, Menu
from api.utils.tokens import login_required


class RoleResource(BaseResource):
    def get(self):
        try:
            roles = Role.query.all()
        except Exception as e:
            print(e)
            return to_response(10020)
        data = [r.to_dict() for r in roles]
        return to_response(200, data=data, msg='获取权限列表成功！')

    def post(self):
        name = request.json.get('name', None)
        desc = request.json.get('desc', None)
        if not name:
            return to_response(10000)
        try:
            role = Role(name=name, desc=desc)
            db.session.add(role)
            db.session.commit()
        except Exception as e:
            return to_response(10020)
        return to_response(200, data=role.to_dict(), msg='添加权限成功！')

    def put(self):
        id = request.json.get('id', None)
        name = request.json.get('name', None)
        desc = request.json.get('desc', None)
        if not all([id, name]):
            return to_response(10000)
        try:
            role = Role.query.get(id)
        except Exception as e:
            return to_response(10020)

        if not role:
            return to_response(10017)

        try:
            role.name = name
            role.desc = desc
            db.session.commit()
            return to_response(200, data=role.to_dict(), msg='修改权限成功！')
        except Exception as e:
            return to_response(10020)

    def delete(self):
        id = request.args.get('id', None)
        if not id:
            return to_response(10000)
        try:
            role = Role.query.get(id)
        except Exception as e:
            return to_response(10020)
        if not role:
            return to_response(10017)

        try:
            db.session.delete(role)
            db.session.commit()
            return to_response(200, msg='删除权限成功！')
        except Exception as e:
            return to_response(10020)


role_api.add_resource(RoleResource, '/role')


@role_blue.route('/del_menu/<int:rid>/<int:mid>/', methods=['GET'])
@login_required
def del_menu(rid, mid):
    try:
        role = Role.query.get(rid)
        menu = Menu.query.get(mid)
    except Exception as e:
        return to_response(10020)

    if not all([role, menu]):
        return to_response(10017)
    try:
        if menu in role.menus:
            role.menus.remove(menu)
            if menu.level == 1:
                for m in menu.children:
                    if m in role.menus:
                        role.menus.remove(m)
            db.session.commit()
        return to_response(200, data=role.get_menu_list(), msg='删除成功！')
    except Exception as e:
        return to_response(10020)


@role_blue.route('/set_menu/', methods=['POST'])
@login_required
def set_menu():
    mids = request.json.get('mids', None)
    rid = request.json.get('rid', None)
    if not all([mids, rid]):
        return to_response(10000)
    try:
        role = Role.query.get(int(rid))
    except Exception as e:
        return to_response(10020)
    if not role:
        return to_response(10000, msg='角色不存在！')
    role.menus = []
    for m in mids.split(','):
        try:
            menu = Menu.query.get(int(m))
        except Exception as e:
            return to_response(10020)
        if menu:
            role.menus.append(menu)
        db.session.commit()
    return to_response(200, msg='角色权限设置成功！')
